import React from 'react'
import { Button, Modal, Tabs, Drawer, Space, Col, Form, Input, Row, Select, Radio ,message} from 'antd';
import { EditOutlined } from '@ant-design/icons';
import useForceUpdate from '../hooks/useForceUpdate'
import{ alterUserApi,getDeptApi,changeUserImgApi }from '../apis/users'
import { useState } from 'react';
export default function Profile() {
  const {username,roleName,ssex,mobile,email,deptName,description,avatar,userId,roleId,status} = JSON.parse(localStorage.user);
  React.useEffect(()=>{
    // console.log(username);
  },[]);
  const forceUpdate = useForceUpdate();
  const userImg = "http://xawn.f3322.net:8002/distremote/static/avatar/" + avatar
  //修改头像
  const [open, setOpen] = useState(false);
  //编辑用户信息
  const [openEdit, setOpenEdit] = useState(false);
  //部门
  const [dept, setDept] = useState([]);
  //表单
  const FormRef = React.useRef(null)
  const img1 = [
      { path: 'http://xawn.f3322.net:8002/distremote/static/avatar/1d22f3e41d284f50b2c8fc32e0788698.jpeg', imgName: '1d22f3e41d284f50b2c8fc32e0788698.jpeg' },
      { path: 'http://xawn.f3322.net:8002/distremote/static/avatar/2dd7a2d09fa94bf8b5c52e5318868b4d9.jpg', imgName: '2dd7a2d09fa94bf8b5c52e5318868b4d9.jpg' },
      { path: 'http://xawn.f3322.net:8002/distremote/static/avatar/17e420c250804efe904a09a33796d5a10.jpg', imgName: '17e420c250804efe904a09a33796d5a10.jpg' },
      { path: 'http://xawn.f3322.net:8002/distremote/static/avatar/17e420c250804efe904a09a33796d5a16.jpg', imgName: '17e420c250804efe904a09a33796d5a16.jpg' },
      { path: 'http://xawn.f3322.net:8002/distremote/static/avatar/496b3ace787342f7954b7045b8b06804.jpeg', imgName: '496b3ace787342f7954b7045b8b06804.jpeg' },
      { path: 'http://xawn.f3322.net:8002/distremote/static/avatar/595ba7b05f2e485eb50565a50cb6cc3c.jpeg', imgName: '595ba7b05f2e485eb50565a50cb6cc3c.jpeg' },
  ]
  const img2 = [
      { path: 'http://xawn.f3322.net:8002/distremote/static/avatar/gaOngJwsRYRaVAuXXcmB.png', imgName: 'gaOngJwsRYRaVAuXXcmB.png' },
      { path: 'http://xawn.f3322.net:8002/distremote/static/avatar/WhxKECPNujWoWEFNdnJE.png', imgName: 'WhxKECPNujWoWEFNdnJE.png' },
      { path: 'http://xawn.f3322.net:8002/distremote/static/avatar/jZUIxmJycoymBprLOUbT.png', imgName: 'jZUIxmJycoymBprLOUbT.png' },
  ]
  const img3 = [
      { path: 'http://xawn.f3322.net:8002/distremote/static/avatar/20180414165909.jpg', imgName: '20180414165909.jpg' },
      { path: 'http://xawn.f3322.net:8002/distremote/static/avatar/20180414165754.jpg', imgName: '20180414165754.jpg' },
      { path: 'http://xawn.f3322.net:8002/distremote/static/avatar/20180414165942.jpg', imgName: '20180414165942.jpg' },
  ]
  //转换头像格式方便tabs渲染
  function showImg(arr) {
      return arr.map(item => {
          return <img src={item.path} alt="" onClick={() => chooseImg(item.imgName)} style={{ width: 96, height: 96, margin: 8, cursor: 'pointer' }} key={item.imgName} />
      })
  }
  const imgArr = [
      {
          label: `后田花子`,
          key: '1',
          children: showImg(img1)
      },
      {
          label: `阿里系`,
          key: '2',
          children: showImg(img2)
      },
      {
          label: `脸萌`,
          key: '3',
          children: showImg(img3)
      },
  ]
  //点击修改头像按钮
  function changImg() {
      setOpen(true)
  }
  //切换头像tab
  const onChange = (key) => {
      console.log(key);
  };
  //选中头像->修改头像
  function chooseImg(params) {
      // console.log('params', params);
      //发接口修改头像数据
      changeUserImgApi({ username:username, avatar: params })
          .then(() => {
              message.success('修改头像成功')
              setOpen(false);
              let user = JSON.parse(localStorage.user)
              //替换本地储存用户信息
              user.avatar = params
              // console.log(userInfo);
              localStorage.user = JSON.stringify(user)
              //触发事件总线，通知index的header更改信息
              eventBus.emit(eventNames.syncUserInfo)
              //强制更新
              forceUpdate()
          })
  }
  //点击进入修改用户信息弹窗
  function editUserInfo() {
      // console.log('editUserInfo');
      setOpenEdit(true);
      //查询所有部门信息
      getDeptApi()
          .then(res => {
              // console.log('dept',res);
              const deptArr = res.rows.children
              setDept(deptArr)
          })
  }
  //关闭修改信息弹窗
  const onClose = () => {
      setOpenEdit(false);
  };
  //表单提交
  const onFinish = (values) => {
      // console.log('success:', values);
      const o = {
          email: values.email,
          mobile: values.mobile,
          ssex: values.ssex,
          description: values.description,
          userId: userId,
          deptName: values.deptName,
          roleId: roleId,
          status: status,
          username: username
      }
      console.log(o);
      //发接口
      alterUserApi(o)
          .then(() => {
              message.success('资料修改成功')
              // 关闭弹出框
              setOpenEdit(false);
              let user = JSON.parse(localStorage.user)
              //更新本地储存
              user.email = o.email
              user.mobile = o.mobile
              user.ssex = o.ssex
              user.description = o.description
              localStorage.user = JSON.stringify(user)
              //强制更新一次
              forceUpdate()
          })


    };
    //点击登录按钮 表单验证失败
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
  return (
    <div style={{padding:'0 15px'}}>
        <div style={{border:'1px solid #eeeeee',}}>
          <div style={{borderBottom:'1px solid #eeeeee',padding:'15px 25px',display:'flex',justifyContent:'flex-end',color:'#1890ff',fontSize:'15px'}} onClick={editUserInfo}>编辑用户</div>
          <div style={{display:'flex',padding:'20px 0 0 60px'}}>
            <div style={{marginRight:'80px',paddingBottom:'30px',width:'160px'}}>
              <img style={{width:'160px',height:'160px'}} src={userImg} alt="" />
              <Button onClick={changImg}>修改头像</Button>
            </div>
            <ul style={{color:'#595959',fontSize:'15px',display:'flex',flexWrap:'wrap',paddingBottom:'10px'}}>
              <li style={{width:'100%'}}>账户：{username}</li>
              <li style={{width:'100%'}}>角色：{roleName}</li>
              <li style={{width:'100%'}}>性别：{ssex}</li>
              <li style={{width:'100%'}}>电话：{mobile}</li>
              <li style={{width:'100%'}}>邮箱：{email}</li>
              <li style={{width:'100%'}}>部门：{deptName ? deptName : '暂无部门'}</li>
              <li style={{width:'100%'}}>描述：{description}</li>
            </ul>
          </div>
        </div>
         {/* 用户头像的模态框 */}
         <Modal
                title="选择头像"
                centered
                open={open}
                onOk={() => setOpen(false)}
                onCancel={() => setOpen(false)}
                width={800}
            >
                <Tabs
                    defaultActiveKey="1"
                    onChange={onChange}
                    items={imgArr}
                />
            </Modal>

            {/* 修改用户信息弹窗 */}
            <Drawer
                title="编辑资料"
                width={720}
                open={openEdit}
                bodyStyle={{
                    paddingBottom: 80,
                }}
                closable={false}
                footer={
                    <Space>
                        <Button onClick={onClose}>取消</Button>
                        <Button onClick={()=> (FormRef.current).submit()} type="primary" >
                            提交
                        </Button>
                    </Space>
                }
                footerStyle={{ textAlign: 'right' }}
            >
                <Form layout="vertical" hideRequiredMark
                    initialValues={{
                        email: email,
                        mobile: mobile,
                        deptName: deptName,
                        description: description,
                        ssex: ssex
                    }}
                    ref={FormRef}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                >
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="email"
                                label="邮箱"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入邮箱',
                                    },
                                ]}
                            >
                                <Input placeholder="请输入邮箱" />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="mobile"
                                label="手机"
                                rules={[
                                    {
                                        required: true,
                                        message: 'Please enter url',
                                    },
                                ]}
                            >
                                <Input placeholder="请输入手机号" />
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="deptName"
                                label="部门"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择部门',
                                    },
                                ]}
                            >
                                <Select>
                                    {
                                        dept.map(item => {
                                            return <Select.Option value={item.id} key={item.id}>{item.text}</Select.Option>
                                        })
                                    }
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item
                                name="ssex"
                                label="性别"
                                rules={[
                                    {
                                        required: true,
                                        message: 'Please choose the approver',
                                    },
                                ]}
                            >
                                <Radio.Group>
                                    <Radio value="0">男</Radio>
                                    <Radio value="1">女</Radio>
                                    <Radio value="2">保密</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </Col>

                    </Row>
                    <Row gutter={16}>
                        <Col span={24}>
                            <Form.Item
                                name="description"
                                label="描述"
                                rules={[
                                    {
                                        required: true,
                                        message: '请输入描述内容',
                                    },
                                ]}
                            >
                                <Input.TextArea rows={4} placeholder="请输入描述内容" />
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Drawer>
    </div>
  )
}
